<template>
  <div class="app-container">
    <div class="filter-container">
      <el-input
        v-model="listQuery.title"
        placeholder="title"
        style="width:200px"
        class="filter-item"
        @keyup.enter.native="handleFilter"
      />
      <el-select
        v-model="listQuery.status"
        placeholder="status"
        clearable
        class="filter-item"
        style="width: 130px"
      >
        <el-option
          v-for="item in calendarStatusOptions"
          :key="item.key"
          :label="item.display_name"
          :value="item.key"
        />
      </el-select>
      <el-button
        class="filter-item"
        type="primary"
        icon="el-icon-search"
        @click="handleFilter"
        :disabled="!permission[0]"
      >Search</el-button>
      <el-button
        class="filter-item"
        style="margin-left: 10px;"
        type="primary"
        icon="el-icon-edit"
        @click="handleCreate"
        :disabled="!permission[1]"
      >Add</el-button>
      <el-button
        :loading="downloadLoading"
        class="filter-item"
        type="primary"
        icon="el-icon-download"
        @click="handleDownload"
      >Export</el-button>
    </div>
    <el-table v-loading="listLoading" :data="list" style="width: 100%;">
      <el-table-column
        label="ID"
        prop="id"
        sortable
        align="center"
         width="50"
        :class-name="getSortClass('id')"
      >
        <template slot-scope="scope">
          <span>{{ scope.row.id }}</span>
        </template>
      </el-table-column>
      <el-table-column label="title" align="center">
        <template slot-scope="{row}">
          <span class="link-type" @click="handleUpdate(row)">{{ row.title }}</span>
        </template>
      </el-table-column>
      <el-table-column label="Date" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.date}}</span>
        </template>
      </el-table-column>
      <el-table-column label="Status" class-name="status-col">
        <template slot-scope="{row}">
          <el-tag :type="row.status | statusFilter">{{ row.status }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="Actions" align="center" class-name="small-padding fixed-width" width="300">
        <template slot-scope="{row}">
          <el-button type="primary" size="mini" @click="handleUpdate(row)" :disabled="!permission[2]">Edit</el-button>
          <el-button
            v-if="row.status!='Workflow'"
            size="mini"
            type="success"
            @click="handleModifyStatus(row,'Workflow')"
            :disabled="!permission[4]"
          >Workflow</el-button>
          <el-button
            v-if="row.status!='Complete'"
            size="mini"
            @click="handleModifyStatus(row,'Complete')"
            :disabled="!permission[4]"
          >Complete</el-button>
          <el-button
            v-if="row.status!='Reject'"
            size="mini"
            type="danger"
            @click="handleModifyStatus(row,'Reject')"
            :disabled="!permission[4]"
          >Reject</el-button>
        </template>
      </el-table-column>
    </el-table>
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="listQuery.page"
      :limit.sync="listQuery.limit"
      @pagination="getList"
    />

    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
      <el-form ref="dataForm" :rules="rules" :model="temp" label-position="left" label-width="70px" style="width: 400px; margin-left:50px;">
        <el-form-item label="title" prop="title">
             <el-input v-model="temp.title" />
        </el-form-item>
        <el-form-item label="Date" prop="date">
              <el-date-picker v-model="temp.date" type="datetime" placeholder="Please pick a date" />
        </el-form-item>
        <el-form-item label="Status" prop="status">
            <el-select v-model="temp.status" class="filter-item" placeholder="Please select">
            <el-option v-for="item in calendarStatusOptions" :key="item.key" :label="item.display_name" :value="item.key" />
          </el-select>
        </el-form-item>
      </el-form>
       <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">
          Cancel
        </el-button>
        <el-button type="primary" @click="dialogStatus==='create'?createData():updateData()">
          Confirm
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
// import { parseTime } from "../../untils/dataFormat";
import fetchList from "../../api/table";
import Pagination from './components/pagination'
import {MathConver} from '../../untils/pagePermission'
// import { mapState } from 'vuex'
const calendarStatusOptions = [
  { key: "Workflow", display_name: "Workflow" },
  { key: "Complete", display_name: "Complete" },
  { key: "Reject", display_name: "Reject" }
];
export default {
  name: "ComplexTable",
  components: { Pagination },
  filters: {
    statusFilter(status) {
      const statusMap = {
        Complete: "success",
        Workflow: "info",
        Reject: "danger"
      };
      return statusMap[status];
    }
  },
  created() {
    this.getList();
    //判断权限
    // console.log("当前路由：",this.$route.meta)
    // console.log("当前页面拥有权限：",this.$store.getters.roles)
    // console.log("当前用户角色：",this.$store.state.user.useInfo.roles)
    // console.log("权限：",this.$store.state.user.PagePermission)
    //如果是系统管理员，则拥有所有权限
    if(this.$store.state.user.useInfo.roles==='Admin'){
      //对应着this.$store.state.user.PagePermission中的权限
      this.permission=[true,true,true,true,true]
    }else{
      this.$store.getters.roles.forEach(item=>{
        if(item.menuName===this.$route.meta.title){
          const arr=MathConver(item.pagePermissions)
          arr.split('').forEach(char=>{
            if(char==='1'){
              this.permission.push(true)
            }else{
              this.permission.push(false)
            }
          })
        }
      })
    }
    console.log("当前页面权限",this.permission)
  },
  data() {
    return {
      permission:[],
      list: null,
      total: 0,
      listLoading: true,
      listQuery: {
        page: 1,
        limit: 10,
        title: undefined,
        status: undefined,
        sort: "+id"
      },
      calendarStatusOptions,
      downloadLoading: false,
      temp:{
        id:undefined,
        title:'',
        date:new Date(),
        status:'Workflow'
      },
      dialogFormVisible: false,
      dialogStatus:'',
      textMap: {
        update: 'Edit',
        create: 'Create'
      },
       rules: {
        status: [{ required: true, message: 'status is required', trigger: 'change' }],
        date: [{ type: 'date', required: true, message: 'date is required', trigger: 'change' }],
        title: [{ required: true, message: 'title is required', trigger: 'blur' }]
      },
    };
  },
  methods: {
    getList() {
      this.listLoading = true;
      fetchList.getList(this.listQuery).then(res => {
        this.list = res.data.data.items;
        this.total = res.data.data.total;
        setTimeout(() => {
          this.listLoading = false;
        }, 1.5 * 1000);
      });
    },
    handleFilter() {
     this.listQuery.page = 1
      this.getList()
    },
    handleCreate() {
       this.resetTemp()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    handleModifyStatus(row,status){
      this.$message({
        message:"操作成功",
        type:'success'
      })
      row.status=status
    },
    handleDownload() {
      this.downloadLoading=true
      //es6语法，import函数，实现动态加载
      import('../../vendor/Export2Excel').then(excel=>{
        const tHeader=['id','Title','Date','Status']
        const filterVal=['id','title','date','status']
        const data = this.formatJson(filterVal, this.list)
        excel.export_json_to_excel({
          header:tHeader,
          data,
          filename:'table-list'
        })
        this.downloadLoading=false
      })
    },
    formatJson(filterVal, jsonData) {
      return jsonData.map(v => filterVal.map(j => {
       //在这可以对数据进行处理
       return v[j]
      }))
    },
    handleUpdate(row){
      if(!this.permission[2]){
        return false;
      }
      this.temp=Object.assign({},row)
      this.temp.date=new Date(this.temp.date)
      this.dialogStatus="update"
      this.dialogFormVisible=true;
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    updateData(){
      this.$refs['dataForm'].validate((valid)=>{
        if(valid){
          const tempData = Object.assign({}, this.temp)
          tempData.date = new Date(tempData.date).toLocaleDateString()
          //模拟更新操作
          this.list.forEach((item,index)=>{
            if(item.id===tempData.id){
              this.list.splice(index,1,tempData)
            }
          })
          this.dialogFormVisible = false
            this.$notify({
              title: 'Success',
              message: 'Update Successfully',
              type: 'success',
              duration: 2000
            })
        }
      })
    },
    createData(){
       this.$refs['dataForm'].validate((valid)=>{
         if(valid){
           this.temp.id = parseInt(Math.random() * 100) + 1024
           //没有写后台增加
           this.list.unshift(this.temp)
           this.dialogFormVisible = false
           this.$notify({
              title: 'Success',
              message: 'Created Successfully',
              type: 'success',
              duration: 2000
            })
         }
       })
    },
    resetTemp(){
      this.temp={
         id:undefined,
        title:'',
        date:new Date(),
        status:'Workflow'
      }
    },
    getSortClass: function(key) {
      const sort = this.listQuery.sort;
      return sort === `+${key}`
        ? "ascending"
        : sort === `-${key}`
        ? "descending"
        : "";
    }
  }
};
</script>
<style lang="scss">
.link-type {
    color:#337ab7;
    cursor: pointer;
}
.link-type:hover{
    color:#423ff3;
}
</style>